# 百度云语音识别模块

from aip import AipSpeech


class BaiduAipSpeech:

    def __init__(self, local_file_path='./recorded_audio.wav'):
        # ================ 心语画笔 APPID AK SK ==========================
        self.APP_ID = '18125783'
        self.API_KEY = 'kC3WO5rzCkQ2QIHg5XU2jYK8'
        self.SECRET_KEY = 'cjNGyjeGEMLjtVIUSbHjPTnqTx2l3s46'

        self.client = AipSpeech(self.APP_ID, self.API_KEY, self.SECRET_KEY)

        self.local_file_path = local_file_path

        self.result = None

    # =========================== 读取文件函数 ============================
    @staticmethod
    def _get_file_content(file_path):
        with open(file_path, 'rb') as fp:
            return fp.read()

    # =========================== 启动云识别 ==============================
    def start_recognition(self):
        self.result = self.client.asr(self._get_file_content(self.local_file_path), 'wav', 16000)  # 上传并识别
        # print(result)
        # print(result['result'])
        if self.result['result'] is not None:
            return self.result['result'][0]
        else:
            return 'failed'

    def print_result(self):
        if self.result['result'] is not None:
            print("语音识别结果: {}".format(self.result['result'][0]))
        else:
            print('上传识别时出现失败')


if __name__ == '__main__':
    baidu_smart_speech = BaiduAipSpeech()
    baidu_smart_speech.start_recognition()
    baidu_smart_speech.print_result()
